<template>
  <div class="content">
    <div class="m-h2-btn-box">
      <h2>{{ $route.query.name }}</h2>
      <div class="u-btn-box">
        <el-button class="u-btn" type="primary" @click="downloadObj()"
          >模板下载</el-button
        >
        <div>
          <el-upload
            ref="uploadExl"
            action
            multiple
            :limit="1"
            :http-request="importObj"
            :before-upload="beforeUploadImg"
            :on-exceed="handleExceed_1"
            :show-file-list="false"
          >
            <el-button type="primary" class="u-btn">批量导入</el-button>
          </el-upload>
        </div>
        <!-- <el-upload action multiple :limit="1" :http-request="importObj" :on-exceed="handleExceed_1">
          <el-button type="primary">批量导入</el-button>
        </el-upload>-->
        <el-button type="primary" @click="addClassHourFn()" class="u-btn"
          >新增课时</el-button
        >
      </div>
    </div>
    <div class="m-switch-box">
      校对读秒：
      <el-switch v-model="value"></el-switch>
    </div>
    <el-table
      :data="tableData"
      border
      row-key="id"
      style="max-width: 100%"
      :show-header="false"
    >
      <el-table-column prop="date" label="日期" width="40">
        <template slot-scope="scope">
          <abbr title="表格内可拖动行">
            <i class="el-icon-sort"></i>
          </abbr>
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="420" label="操作">
        <template slot-scope="scope">
          <div class="u-info-div" @click="toClassHourDetails(scope.row)">
            <abbr :title="abbrAll(scope)">
              <h2>第{{ scope.$index + 1 }}讲 {{ scope.row.name }}</h2>
            </abbr>
            <abbr :title="scope.row.description">
              <p>{{ fontLength(scope.row.description) }}</p>
            </abbr>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" width="670" label="操作">
        <template slot-scope="scope">
          <!-- <el-popover placement="bottom" title width="0px" trigger="hover" content> -->
          <!-- <span class="u-hover-box">
              <i class="el-icon-view"></i>
              <i class="el-icon-download"></i>
              <i class="el-icon-delete"></i>
          </span>-->
          <div>
            <div class="z-flex">
              <el-upload
                action
                multiple
                :limit="1"
                ref="uploadZip"
                :http-request="uploadImg"
                :on-exceed="handleExceed_1"
              >
                <!-- :file-list="fileList" -->
                <el-button
                  class="u-mar-right"
                  type="primary"
                  size="small"
                  @click="updateCourseware(scope.row, 'teacher')"
                  >主讲课件
                  {{
                    scope.row.course_num ? scope.row.course_num : 0
                  }}</el-button
                >
              </el-upload>

              <el-upload
                action
                multiple
                :limit="1"
                ref="uploadStudentZip"
                :http-request="uploadStudentImg"
                :on-exceed="handleExceed_2"
              >
                <!-- :file-list="fileList" -->
                <el-button
                  class="u-mar-right"
                  type="primary"
                  size="small"
                  @click="updateCourseware(scope.row, 'student')"
                  >学生课件
                  {{
                    scope.row.student_course_ware_num
                      ? scope.row.student_course_ware_num
                      : 0
                  }}</el-button
                >
              </el-upload>
              <!-- </el-popover> -->
              <!-- <el-popover placement="bottom" title width="0px" trigger="hover" content> -->
              <!-- <span class="u-hover-box">
              <i class="el-icon-view"></i>
              <i class="el-icon-download"></i>
              <i class="el-icon-delete"></i>
              </span>-->

              <el-upload
                action
                multiple
                :limit="30"
                ref="uploadArr"
                :http-request="uploadImgArr"
                :on-exceed="handleExceed_10"
                :on-change="handlePreview"
              >
                <!-- :file-list="fileList" -->
                <el-button
                  type="primary"
                  size="small"
                  @click="updateMaterial(scope.row)"
                  >素材
                  {{
                    scope.row.merterial_num ? scope.row.merterial_num : 0
                  }}</el-button
                >
                <el-progress
                  :percentage="percentage"
                  v-show="showRentPrise && uploadId == scope.row.id"
                ></el-progress>
              </el-upload>
            </div>
            <div>
              <el-popover
                placement="bottom"
                title
                width="30px"
                trigger="hover"
                content
              >
                <span class="u-hover-box">
                  <i class="el-icon-view"></i>
                  <i class="el-icon-download"></i>
                  <i class="el-icon-delete"></i>
                </span>
                <el-button slot="reference" type="primary" size="small"
                  >预习题</el-button
                >
              </el-popover>
              <el-popover
                placement="bottom"
                title
                width="30px"
                trigger="hover"
                content
              >
                <span class="u-hover-box">
                  <i class="el-icon-view"></i>
                  <i class="el-icon-download"></i>
                  <i class="el-icon-delete"></i>
                </span>
                <el-button slot="reference" type="primary" size="small"
                  >课堂练</el-button
                >
              </el-popover>

              <el-popover
                placement="bottom"
                title
                width="30px"
                trigger="hover"
                content
              >
                <span class="u-hover-box">
                  <i class="el-icon-view"></i>
                  <i class="el-icon-download"></i>
                  <i class="el-icon-delete"></i>
                </span>
                <el-button slot="reference" type="primary" size="small"
                  >课后题</el-button
                >
              </el-popover>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope" width="50">
          <el-popconfirm
            title="确定要删除该课时？"
            @onConfirm="deleteList(scope.row, scope)"
          >
            <el-button
              slot="reference"
              type="danger"
              :disabled="status"
              size="small"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <add-class-hour
      :addClassHourShow="addClassHourShow"
      @childFn="getCourseLessonList"
    ></add-class-hour>
  </div>
</template>
<script>
import Sortable from 'sortablejs'
import { ossUploadFile } from '@/api/mixins'
import {
  tableSort,
  courseWareupload,
  materialUpload,
  downloadTemplateFile,
  importData,
  lessonDelete
} from '@/api/course.js'
import {
  // tableUpdate,
  tableDeleted,
  cascadeQuery,
  ossUploadZip,
  ossUpload
} from '@/api/api.js'
import addClassHour from './components/add-class-hour.vue'
export default {
  components: { addClassHour },
  data () {
    return {
      fileListLength: 0,
      value: '',
      addClassHourShow: false,
      showRentPrise: false,
      role: '',
      // progress: 0,
      tableData: [],
      progressFlag: false,
      uploadId: '',
      uploadArr: [],
      status: false,
      percentage: 0
      // fileLength :
    }
  },
  activated () {
    this.$route.query.status == true
      ? (this.status = true)
      : (this.status = false)
    this.getCourseLessonList()
  },
  mounted () {},
  methods: {
    progress (percentage, checkpoint, res) {
      this.percentage = parseInt(percentage * 100)
    },
    // 上传主讲课件
    async uploadImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUploadZip(formData)
      if (res[0]) {
        return
      }
      let url = res[1].data
      let res2 = await courseWareupload({
        'nice_course_ware.name': e.file.name,
        'nice_course_ware.links': url,
        'nice_course_lesson.id': this.uploadId
      })
      if (res2[0]) {
        return
      }
      this.getCourseLessonList()
      this.$ref.uploadZip.clearFiles()
    },
    // 上传学生课件
    async uploadStudentImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUploadZip(formData)
      if (res[0]) {
        return
      }
      let url = res[1].data
      let res2 = await courseWareupload({
        'nice_course_ware.student_links_name': e.file.name,
        'nice_course_ware.student_links': url,
        'nice_course_lesson.id': this.uploadId
      })
      if (res2[0]) {
        return
      }
      this.getCourseLessonList()
      this.$ref.uploadStudentZip.clearFiles()
    },
    // 上传素材
    async uploadImgArr (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let url = await ossUploadFile(this, e, 'MATERIAL_RESOURCE')
      this.uploadArr.push({
        name: e.file.name,
        path: url,
        lesson_merterial: [
          {
            course_id: this.$route.query.id,
            course_lesson_id: this.uploadId
          }
        ]
      })
      // console.log(this.uploadArr.length, this.fileListLength)
      if (this.uploadArr.length === this.fileListLength) {
        let res2 = await materialUpload({
          'vo.course_lesson_id': this.uploadId,
          'vo.list': this.uploadArr
        })
        if (res2[0]) {
          return
        }
        this.getCourseLessonList()
        this.uploadArr = []
        this.fileListLength = 0
      }
      this.$ref.uploadArr.clearFiles()
    },
    handlePreview (file, fileList) {
      console.log(file, fileList)

      if (this.fileListLength < fileList.length) {
        this.fileListLength = fileList.length
      }
    },
    handleExceed_10 (files, fileList) {
      this.fileListLength = fileList.length
      this.$message.warning(
        `当前限制选择 30 个文件，本次选择了 ${files.length} 个文件`
      )
    },
    handleExceed_1 (files, fileList) {
      this.files = files
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件`
      )
    },
    handleExceed_2 (files, fileList) {
      // this.files = files
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件`
      )
    },
    // // 上传课件
    updateCourseware (e, role) {
      this.uploadId = e.id
      this.role = role
      // this.$refs.courseware.click()
    },
    // 上传素材
    updateMaterial (e) {
      this.uploadArr = []
      this.uploadId = e.id
      // this.$refs.material.click()
    },
    // 删除
    async deleteList (e, scope) {
      let res = await lessonDelete([
        {
          table_name: 'nice_course_lesson',
          where: {
            id: [e.id]
          }
        }
      ])
      if (res[0]) {
        return
      }
      this.$message({
        message: '删除成功',
        type: 'success'
      })
      this.tableData.splice(scope.$index, 1)
      this.tableData.forEach((ele, index) => {
        ele.sort = index + 1
      })
      console.log(e.id)
    },
    // 获取列表
    async getCourseLessonList () {
      let res = await cascadeQuery({
        table_name: 'nice_course_lesson',
        condition: [{ course_id: [{ '=': this.$route.query.id }] }],
        member: 'merterial_num,course_num,student_course_ware_num',
        by_order: 'sort'
      })
      if (res[0]) {
        return
      }
      this.tableData = res[1].data
      this.rowDrop()
    },
    abbrAll (e) {
      let a = parseInt(e.$index) + 1
      return '第' + a + '讲 ' + e.row.name
    },
    // 获取前30字
    fontLength (e) {
      if (e && e.length > 30) {
        return e.substr(0, 30) + '...'
      } else {
        return e
      }
    },
    // 前往课时编辑页
    toClassHourDetails (e) {
      this.$router.push({
        name: 'class-hour-details',
        query: {
          id: e.id,
          courseId: this.$route.query.id,
          name: this.$route.query.name,
          sort: e.sort
        }
      })
    },
    // 预览在线文件
    browseDoc (url) {
      let onlineViewType = ['doc', 'docx', 'xls', 'xlsx', 'xlsm', 'ppt', 'pptx']
      let fileTypeName = url
        .substring(url.lastIndexOf('.') + 1, url.length)
        .split('?')[0]
      let isWord = onlineViewType.find(type => type === fileTypeName)
      if (isWord) {
        url = 'http://view.officeapps.live.com/op/view.aspx?src=' + url
      }
      window.open(url, '_blank')
    },
    // 行拖拽
    rowDrop () {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        onEnd ({ newIndex, oldIndex }) {
          // 拖动完成
          console.log(newIndex, oldIndex)
          _this.updateSort(newIndex + 1, _this.tableData[oldIndex].id)
          // _this.getCourseLessonList()
          const currRow = _this.tableData.splice(oldIndex, 1)[0]
          _this.tableData.splice(newIndex, 0, currRow)
          // _this.tableData = JSON.parse(JSON.stringify(_this.tableData))
        }
      })
    },
    // 拖动修改排序
    async updateSort (e, id) {
      console.log(e, id, 'asdasda')
      let res = await tableSort({
        tableName: 'nice_course_lesson',
        primaryKeyValue: id,
        sort: e,
        params: {
          course_id: this.$route.query.id
        }
      })
      if (res[0]) {
      }
    },
    async downloadObj () {
      let res = await downloadTemplateFile({
        data: [
          // { header: '课程id', tableandfield: 'nice_course_lesson.course_id' },
          { header: '讲次标题', tableandfield: 'nice_course_lesson.name' },
          { header: '简介', tableandfield: 'nice_course_lesson.description' }
          // { header: '排序', tableandfield: 'nice_course_lesson.sort' }
        ]
      })
      if (res.status === 200) {
        let filename = decodeURI('课时模板下载.xlsx')
        filename = filename.replace(/\"/g, '')
        this.$downloadExcel(res.data, filename)
      }
      console.log(res)
    },
    async importObj (e) {
      // 导入
      let formData = new FormData()
      formData.append('file', e.file)
      formData.append('course_id', this.$route.query.id)
      let res = await importData(formData)
      if (res[0]) {
        console.log(res)
      }
      this.getCourseLessonList()
      this.$ref.uploadExl.clearFiles()
    },
    // 上传封面前验证
    beforeUploadImg (file) {
      const isExcel =
        file.type === 'application/vnd.ms-excel' ||
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isExcel) {
        this.$message.error('请使用正确格式导入文件')
      }
      if (!isLt10M) {
        this.$message.error('上传的封面图片大小不能超过 10MB!')
      }
      return isExcel && isLt10M
    },
    addClassHourFn () {
      this.addClassHourShow = !this.addClassHourShow
    }
  }
}
</script>
<style scoped>
.m-h2-btn-box {
  display: flex;
  justify-content: space-between;
}
.u-btn-box {
  padding-top: 5px;
  display: flex;
}
.u-hover-box i {
  cursor: pointer;
  margin-left: 18px;
}
.u-info-div {
  min-height: 70px;
  cursor: pointer;
}
abbr {
  text-decoration: none;
}
.m-switch-box {
  margin-bottom: 20px;
}
.u-mar-right {
  margin-right: 4px;
}
/* .content >>>  tr:hover{
    background-color:#ffffff!important
} */
/* .content >>> .hover-row { background-color:#ffffff!important } */
/* .content >>> .el-table__row:hover> td{
        background: #fff !important;
    } */

.upload-demo {
}
.z-flex {
  display: flex;
  float: left;
  margin-right: 4px;
}
.z-flex >>> .el-upload-list {
  display: none;
}
.u-btn {
  margin: 5px;
  width: 100px;
  height: 40px;
}
</style>
